import React from 'react';
import { Tabs, Button, Icon, Card, Divider, Row, Table, Typography, Tooltip, message } from 'antd';
import { eventTrack } from '@/utils/track';
import { router, Link } from 'umi';
import AuthComponent from '@/utils/auth/AuthComponent';
import IconFont from '@/components/IconFont';
import { useGradeTypes, useGrades } from './hooks';
import { STATE_MAP, FORM_TYPE_MAP } from './utils';
import { deleteRankCheck } from './service';
import styles from './style.less';

const List = () => {
    const [rankTypeCode, setRankTypeCode] = React.useState();
    const [gradeTypesLoading, gradeTypes] = useGradeTypes();
    const gradesQuery = React.useMemo(() => ({ rankTypeCode }), [rankTypeCode]);
    const [gradesLoading, grades] = useGrades(gradesQuery);

    // 默认选中职级类型
    React.useEffect(() => {
        if (gradeTypes.length !== 0) {
            setRankTypeCode(String(gradeTypes[0].rankTypeCode));
        }
    }, [gradeTypes]);

    React.useEffect(() => {
        // 不使用setTimeout拿到的是展开的内容
        setTimeout(() => {
            const nodeList = document.querySelectorAll('.dimension-paragraph > span') || [];
            if (nodeList.length) {
                nodeList.forEach(dom => {
                    dom.setAttribute('title', '');
                });
            }
        }, 0);
    }, [grades]);

    // 当前职级类型
    const gradeType = React.useMemo(() => gradeTypes.find(item => String(item.rankTypeCode) === rankTypeCode) || {}, [
        gradeTypes,
        rankTypeCode
    ]);

    React.useEffect(() => {
        eventTrack({
            eventName: 'personnel_management_organization_ranklist_click',
            pageName: 'personnel_management_organization'
        });
    }, []);

    const getDimensionContent = (text, row) => (
        <Typography.Paragraph
            className="dimension-paragraph"
            ellipsis={{ rows: 7, expandable: true }}
            style={{ whiteSpace: 'pre-line', marginBottom: 0 }}
        >
            {text}
            {text && (
                <>
                    <span
                        style={{
                            display: 'inline-block',
                            marginBottom: row.rankDimensions && row.rankDimensions.length > 0 ? '14px' : 0
                        }}
                    >
                        &nbsp;
                    </span>
                    <br />
                </>
            )}
            {/* {row.rankDimensions &&
                row.rankDimensions.length > 0 &&
                row.rankDimensions.map(item => (
                    <span className={styles.dimensionItem}>
                        <span className={styles.dimensionName}>{`· ${item.dimensionTypeName}：`}</span>
                        <span>{item.demand}</span>
                        <br />
                    </span>
                ))} */}
        </Typography.Paragraph>
    );

    const columns = [
        {
            title: '职级名称',
            dataIndex: 'rankName',
            key: 'rankName',
            width: 100,
            render: text => (
                <Typography.Text style={{ width: 100, marginBottom: 0 }} title={text}>
                    {text}
                </Typography.Text>
            )
        },
        {
            title: '职级',
            dataIndex: 'rankValue',
            key: 'rankValue',
            width: 100
        },
        {
            title: '职级定义',
            dataIndex: 'rankDesc',
            key: 'rankDesc',
            width: 400,
            render: (text, row) => getDimensionContent(text, row)
        },
        {
            title: '关联职位',
            dataIndex: 'positionCount',
            key: 'positionCount',
            align: 'center',
            width: 100,
            render: (text, record) => {
                if (!text) {
                    return '-';
                }
                return (
                    <Tooltip title="关联职位个数，点击可打开职位管理" overlayStyle={{ width: 150 }}>
                        <Link
                            // 埋点
                            onClick={() => {
                                eventTrack({
                                    eventName: 'organization_rank_post_click',
                                    eventProps: { label: '职级管理-查看关联职位', rank: record.rankCode }
                                });
                            }}
                            to={{
                                pathname: '/office/personnelManagement/organization/job',
                                query: { rankCodeList: [record.rankCode] },
                                state: { tabRoute: true, tabRefresh: true }
                            }}
                        >
                            {text}
                        </Link>
                    </Tooltip>
                );
            }
        },
        {
            title: '状态',
            dataIndex: 'state',
            key: 'state',
            width: 140,
            render: (text, record) => {
                const Text = <span>{STATE_MAP[text]}</span>;
                if ([1, 4].includes(record.state)) {
                    return (
                        <>
                            {Text}
                            <Tooltip title="变更申请在审批中，当前展示为旧版本" overlayStyle={{ width: 150 }}>
                                <Icon type="question-circle" style={{ marginLeft: 4 }} />
                            </Tooltip>
                        </>
                    );
                }
                if ([2, 5].includes(record.state)) {
                    return (
                        <>
                            {Text}
                            <Tooltip
                                title="制度变更已通过审批，当前展示为旧版本，新版本将在生效日当天自动更新"
                                overlayStyle={{ width: 150 }}
                            >
                                <Icon type="question-circle" style={{ marginLeft: 4 }} />
                            </Tooltip>
                        </>
                    );
                }
                return Text;
            }
        },
        {
            title: '审批人',
            dataIndex: 'approveEmployeeName',
            key: 'approveEmployeeName',
            width: 150,
            render: (_, record) => `${record.approveEmployeeName || ''}-${record.approvePostName || ''}`
        },
        {
            title: '操作',
            dataIndex: 'address',
            key: 'address',
            width: 150,
            render(_, record) {
                return (
                    <>
                        {record.state === 0 && (
                            <>
                                <AuthComponent code="office:orgs:views:level:edit">
                                    <Tooltip title="编辑">
                                        <IconFont
                                            isButton
                                            icon="iconlistfunction_edit_icon_default"
                                            style={{ fontSize: '24px', marginRight: !record.positionCount ? 8 : 23 }}
                                            // 埋点
                                            onClick={() => {
                                                eventTrack({
                                                    eventName: 'organization_rank_edit_click',
                                                    eventProps: { label: '职级定义-编辑职级', rank: record.rankCode }
                                                });
                                                history.push({
                                                    pathname: '/office/personnelManagement/organization/rank/edit',
                                                    query: {
                                                        type: 'edit',
                                                        category: 'postRank',
                                                        rankCode: record.rankCode,
                                                        rankTypeCode
                                                    }
                                                });
                                            }}
                                        />
                                    </Tooltip>
                                </AuthComponent>

                                {!record.positionCount && (
                                    <AuthComponent code="office:orgs:views:level:del">
                                        <Tooltip title="删除">
                                            <IconFont
                                                isButton
                                                icon="iconlistfunction_delete_icon_default"
                                                style={{ fontSize: '24px', marginRight: 8 }}
                                                onClick={async () => {
                                                    eventTrack({
                                                        eventName: 'organization_rank_delete_click',
                                                        eventProps: {
                                                            label: '职级定义-删除职级序列',
                                                            rank: record.rankCode
                                                        }
                                                    });
                                                    const result = await deleteRankCheck({ rankCode: record.rankCode });
                                                    if (result?.code === 10000) {
                                                        history.push({
                                                            pathname:
                                                                '/office/personnelManagement/organization/rank/edit',
                                                            query: {
                                                                type: 'delete',
                                                                category: 'postRank',
                                                                rankCode: record.rankCode,
                                                                rankTypeCode
                                                            }
                                                        });
                                                        // deleteRank('postRank', record.rankCode, gradeType.rankTypeName);
                                                    } else {
                                                        message.error(result?.msg);
                                                    }
                                                }}
                                            />
                                        </Tooltip>
                                    </AuthComponent>
                                )}
                            </>
                        )}
                        <Tooltip title="历史">
                            <IconFont
                                isButton
                                icon="iconlistfunction_history_icon_default"
                                style={{ fontSize: '24px' }}
                                onClick={() => {
                                    eventTrack({
                                        eventName: 'organization_rank_history_click',
                                        eventProps: { label: '职级定义-编辑历史', rank: record.rankCode }
                                    });
                                    history.push({
                                        pathname: '/office/personnelManagement/organization/rank/history',
                                        query: {
                                            code: record.rankCode,
                                            type: FORM_TYPE_MAP[1]
                                        }
                                    });
                                }}
                            />
                        </Tooltip>
                    </>
                );
            }
        }
    ];

    const operations = (
        <>
            <AuthComponent code="office:orgs:views:level:addtype">
                <Tooltip title="新增职级序列">
                    <Button
                        onClick={async () => {
                            await eventTrack({
                                eventName: 'organization_rank_category_add_click',
                                eventProps: { label: '新增职级序列' }
                            });
                            history.push({
                                pathname: '/office/personnelManagement/organization/rank/edit',
                                query: {
                                    type: 'add',
                                    category: 'postRankType'
                                }
                            });
                        }}
                        className={styles.btnIcon}
                    >
                        <IconFont icon="iconconstruct_unfold_o" style={{ fontSize: '24px' }} />
                    </Button>
                </Tooltip>
            </AuthComponent>

            {gradeType.state === 0 && (
                <>
                    <AuthComponent code="office:orgs:views:level:edittype">
                        <Tooltip title="编辑职级序列">
                            <Button
                                style={{ marginLeft: 16 }}
                                onClick={async () => {
                                    // 埋点
                                    await eventTrack({
                                        eventName: 'organization_rank_category_edit_click',
                                        eventProps: { label: '编辑职级序列', rank_category: gradeType.rankTypeName }
                                    });

                                    history.push({
                                        pathname: '/office/personnelManagement/organization/rank/edit',
                                        query: {
                                            type: 'edit',
                                            category: 'postRankType',
                                            rankTypeCode
                                        }
                                    });
                                }}
                                className={styles.btnIcon}
                            >
                                <IconFont icon="iconlistfunction_edit_icon_default" style={{ fontSize: '24px' }} />
                            </Button>
                        </Tooltip>
                    </AuthComponent>

                    {!gradesLoading && !grades.length && (
                        <AuthComponent code="office:orgs:views:level:deltype">
                            <Tooltip title="删除职级序列">
                                <Button
                                    style={{ marginLeft: 16 }}
                                    onClick={async () => {
                                        if (grades.length !== 0) {
                                            message.error('职级序列下有可用职级，不可删除');
                                            return;
                                        }

                                        // 埋点
                                        await eventTrack({
                                            eventName: 'organization_rank_category_delete_click',
                                            eventProps: { label: '删除职级序列', rank_category: gradeType.rankTypeName }
                                        });

                                        history.push({
                                            pathname: '/office/personnelManagement/organization/rank/edit',
                                            query: {
                                                type: 'delete',
                                                category: 'postRankType',
                                                rankTypeCode
                                            }
                                        });
                                        // deleteRank('postRankType', gradeType.rankTypeCode);
                                    }}
                                    className={styles.btnIcon}
                                >
                                    <IconFont
                                        icon="iconlistfunction_delete_icon_default"
                                        style={{ fontSize: '24px' }}
                                    />
                                </Button>
                            </Tooltip>
                        </AuthComponent>
                    )}
                </>
            )}

            {gradeTypes.length !== 0 && (
                <Tooltip title="历史">
                    <Button
                        style={{ marginLeft: 16 }}
                        // 埋点
                        onClick={async () => {
                            await eventTrack({
                                eventName: 'organization_rank_category_history_click',
                                eventProps: { label: '历史', rank_category: gradeType.rankTypeName }
                            });
                            history.push({
                                pathname: '/office/personnelManagement/organization/rank/history',
                                query: { code: rankTypeCode, type: FORM_TYPE_MAP[0] }
                            });
                        }}
                        className={styles.btnIcon}
                    >
                        <IconFont icon="iconlistfunction_history_icon_default" style={{ fontSize: '24px' }} />
                    </Button>
                </Tooltip>
            )}
        </>
    );

    const handleChange = key => {
        setRankTypeCode(key);
        eventTrack({
            eventName: 'organization_rank_category_label_click',
            eventProps: { label: gradeType.rankTypeName }
        });
    };

    const renderTabs = React.useCallback(
        () => gradeTypes.map(item => <Tabs.TabPane tab={item.rankTypeName} key={item.rankTypeCode}></Tabs.TabPane>),
        [gradeTypes]
    );

    const renderGradeTypeState = () => {
        const Text = <span>{STATE_MAP[gradeType.state]}</span>;
        if ([1, 4].includes(gradeType.state)) {
            return (
                <>
                    {Text}
                    <Tooltip title="变更申请在审批中，当前展示为旧版本" overlayStyle={{ width: 150 }}>
                        <Icon type="question-circle" style={{ marginLeft: 4 }} />
                    </Tooltip>
                </>
            );
        }
        if ([2, 5].includes(gradeType.state)) {
            return (
                <>
                    {Text}
                    <Tooltip
                        title="制度变更已通过审批，当前展示为旧版本，新版本将在生效日当天自动更新"
                        overlayStyle={{ width: 150 }}
                    >
                        <Icon type="question-circle" style={{ marginLeft: 4 }} />
                    </Tooltip>
                </>
            );
        }
        return Text;
    };

    return (
        <Card
            title="职级管理"
            style={{ margin: '12px 16px 16px 16px', background: '#fff' }}
            loading={gradeTypesLoading}
        >
            <Tabs
                tabBarExtraContent={operations}
                activeKey={rankTypeCode}
                onChange={handleChange}
                className={styles.tabs}
            >
                {renderTabs()}
            </Tabs>
            {gradeTypes.length !== 0 && (
                <>
                    <div className={styles.title} style={{ marginTop: 24 }}>
                        职级序列
                    </div>
                    <div className={styles.definitionItem}>
                        <div>描述：</div>
                        <div>
                            <Typography.Paragraph
                                style={{ marginBottom: 0, whiteSpace: 'pre-line' }}
                                title={gradeType.rankTypeDesc}
                                ellipsis={{ rows: 3, expandable: true }}
                            >
                                {gradeType.rankTypeDesc}
                            </Typography.Paragraph>
                        </div>
                    </div>
                    <div className={styles.definitionItem}>
                        <div>状态：</div>
                        <div span={10}>{renderGradeTypeState()}</div>
                    </div>
                    <div className={styles.definitionItem}>
                        <div>审批人：</div>
                        <div>{`${gradeType.approveEmployeeName || ''}-${gradeType.approvePostName || ''}`}</div>
                    </div>
                    <Divider />
                </>
            )}

            {gradeTypes.length !== 0 && (
                <>
                    <Row type="flex" justify="space-between" style={{ marginBottom: 16 }}>
                        <div className={styles.title}>职级定义</div>
                        {![4, 5].includes(gradeType.state) && (
                            <>
                                <AuthComponent code="office:orgs:views:level:add">
                                    <Tooltip title="新增职级">
                                        <Button
                                            onClick={async () => {
                                                await eventTrack({
                                                    eventName: 'organization_rank_add_click',
                                                    eventProps: { label: '新增职级' }
                                                });
                                                history.push({
                                                    pathname: '/office/personnelManagement/organization/rank/edit',
                                                    query: {
                                                        type: 'add',
                                                        category: 'postRank',
                                                        rankTypeCode
                                                    }
                                                });
                                            }}
                                            className={styles.btnIcon}
                                        >
                                            <IconFont icon="iconconstruct_unfold_o" style={{ fontSize: '24px' }} />
                                        </Button>
                                    </Tooltip>
                                </AuthComponent>
                            </>
                        )}
                    </Row>
                    <Table
                        rowKey="rankCode"
                        dataSource={grades}
                        columns={columns}
                        loading={gradesLoading}
                        pagination={false}
                    />
                </>
            )}
        </Card>
    );
};

export default List;
